import cv2
import numpy as np
import random

# 创建一个黑色背景
width, height = 800, 600
background = np.zeros((height, width, 3), dtype=np.uint8)

# 设置球的半径
radius = 30

# 设置球的速度
speed = 2

# 存储球的列表
balls = []

# 视频相关参数
output_file = 'bouncing_balls_video.avi'
fps = 30
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video_writer = cv2.VideoWriter(output_file, fourcc, fps, (width, height))

# 主循环
while True:
    # 清空画布
    background = np.zeros((height, width, 3), dtype=np.uint8)

    # 随机生成一个球的位置
    if random.random() < 0.02:  # 调整生成球的概率
        x = -radius
        y = random.randint(radius, height - radius)

        # 检查新球的位置与已有球的位置是否过于接近，如果是，则重新生成位置
        overlap = any(np.sqrt((x - ball["x"])**2 + (y - ball["y"])**2) < 2 * radius for ball in balls)
        if not overlap:
            balls.append({"x": x, "y": y, "radius": radius, "speed": speed})

    # 更新和绘制所有球
    for ball in balls:
        ball["x"] += ball["speed"]

        # 如果球从右侧出去，则从列表中移除
        if ball["x"] > width + ball["radius"]:
            balls.remove(ball)
        else:
            # 绘制球
            cv2.circle(background, (int(ball["x"]), int(ball["y"])), ball["radius"], (255, 255, 255), -1)

    # 将当前帧写入视频文件
    video_writer.write(background)

    # 显示画布
    cv2.imshow("Bouncing Balls", background)

    # 检查按键事件，如果按下ESC键，则退出循环
    key = cv2.waitKey(1)
    if key == 27:
        break

# 释放视频写入器
video_writer.release()

# 释放窗口
cv2.destroyAllWindows()
